package edu.zut.test;

import edu.zut.main.pojo.SysUser;

import java.sql.*;

/**
* 基于JDBS操作数据库
*/
public class JDBCtest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /**
         * 1、加载驱动   Class.forName();  是否每一次操作都需要？
         * 2、获取数据库连接    利用jdk提供的技术
         * 3、定义sql
         * 4、执行sql(增删查改)
         * 5、处理执行结果
         * 6、资源释放
         *
         */
        Class.forName("com.mysql.cj.jdbc.Driver");
        //基于数据库url，用户名，密码获取连接对象
        String url = "jdbc:mysql://127.0.0.1:3306/class?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "qwer1234";
        Connection connection = DriverManager.getConnection(url,user,password);
//        System.out.println("connection = " + connection);
        //编写sql  ?占位符，后期会自动替换
        String sql = "select * from sys_user where user_name=? and user_password=?";
        //处理sql    PreparedStatement预处理sql
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,"小郭");
        statement.setString(2,"1234");
        //执行sql     executeQuery查询(返回结果集)  executeUpdate增删改(返回int表示受影响的数据)
        ResultSet rs = statement.executeQuery();
        SysUser sysUser = null;
        //执行结果
        while(rs.next()){
            //解析每一行获取的字段数据
            int user_id = rs.getInt("user_id");
            String user_code = rs.getString("user_code");
            String user_name = rs.getString("user_name");
            String user_password = rs.getString("user_password");
            sysUser = new SysUser(user_id,user_code,user_name,user_password);
        }
        System.out.println(sysUser);
        //资源释放
        rs.close();
        statement.close();
        connection.close();
    }
}
